package com.netty.demo10;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * Created by Lxk on 2020/2/2.
 */
public class NioTest11 {
    //Scattering与Gathering，前者将读取的内容分散到多个buffer中（即buffer数组，一个一个填满，然后填充下一个）
    //Gathering将多个buffer中的内容合并到一个channel中输出写入给外部
    public static void main(String[] args) throws  Exception{
        ServerSocketChannel socketChannel = ServerSocketChannel.open();
        InetSocketAddress socketAddress = new InetSocketAddress(8899);
        socketChannel.socket().bind(socketAddress);

        int messageLength = 2 + 3 + 4;
        ByteBuffer[] buffers = new ByteBuffer[3];

        buffers[0] = ByteBuffer.allocate(2);
        buffers[1] = ByteBuffer.allocate(3);
        buffers[2] = ByteBuffer.allocate(4);

        SocketChannel channel = socketChannel.accept();
        while(true){
            int byteRead = 0;
            while(byteRead<messageLength){
                long r = channel.read(buffers);
                byteRead += r;
                System.out.println("byteRead: " + byteRead);
                Arrays.asList(buffers).stream()
                      .map(buffer -> "position: " + buffer.position() + ",limit: " + buffer.position())
                      .forEach(System.out::println);
            }

            Arrays.asList(buffers).forEach(buffer -> {
                buffer.flip();
            });

            long bytesWritten = 0;
            while(bytesWritten<messageLength){
                long r = channel.write(buffers);
                bytesWritten += r;
            }
            Arrays.asList(buffers).forEach(buffer -> {
                buffer.clear();
            });
            System.out.println("bytesRead: " + byteRead + " ,bytesWritten: " + bytesWritten + " ,messageLength:" + messageLength);
        }
    }

}
